﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Backend.BLL;
using Backend.DTO;
using System.Globalization;

namespace ReSeSSApplication
{
    public partial class ChangePassword : System.Web.UI.Page
    {
        UserBLL aUserBll = new UserBLL();
        protected UserDTO loggedInUserDTO = new UserDTO();

        protected void Page_Load(object sender, EventArgs e)
        {
            AlertSuccess.Visible = false;
            AlertError.Visible = false;

            loggedInUserDTO = (UserDTO)Session["LoggedInUserDTO"];
            RedirectUser(loggedInUserDTO);
        }

        protected void ChangePasswordButton_Click(object sender, EventArgs e)
        {
            string oldPassword = txtOldPassword.Text.Trim();
            string newPassword = txtPassword.Text.Trim();
            string confirmPassword = txtConfirmPassword.Text.Trim();

            if (oldPassword == string.Empty || newPassword == string.Empty || confirmPassword == string.Empty)
            {
                AlertError.InnerText = "Required fields cannot be empty";
                AlertError.Visible = true;
                return;
            }

            if (loggedInUserDTO.Password != oldPassword)
            {
                AlertError.InnerText = "Current password does not match.";
                AlertError.Visible = true;
                return;
            }

            if (newPassword != confirmPassword)
            {
                AlertError.InnerText = "Confirm Password does not match with new password";
                AlertError.Visible = true;
                return;
            }

            try
            {
                if (aUserBll.ChangePassword(loggedInUserDTO, newPassword))
                {
                    loggedInUserDTO.Password = newPassword;
                    Session["LoggedInUserDTO"] = loggedInUserDTO;

                    AlertSuccess.InnerHtml = "Your password changed successfully";
                    AlertSuccess.Visible = true;
                }
            }
            catch (Exception ex)
            {
                AlertError.InnerText = ex.Message;
                AlertError.Visible = true;
            }
        }

        protected void RedirectUser(UserDTO userDTO)
        {
            if (userDTO == null)
            {
                Response.Redirect("Index.aspx");
            }
        }
    }
}